package net.wicp.tams.common.others;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

/***
 * ssh2的连接
 * 
 * @author zhoujunhui
 *
 */
public class Ssh2Util {
	private final static Map<String, Connection> conns = new HashMap<String, Connection>();

	private static volatile Ssh2Util INSTANCE;

	private Ssh2Util() {

	}

	public static final Ssh2Util getInstance() {
		if (INSTANCE == null) {
			synchronized (Ssh2Util.class) {
				if (INSTANCE == null) {
					INSTANCE = new Ssh2Util();
				}
			}
		}
		return INSTANCE;
	}

	/***
	 * 连接服务器
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param isForce
	 *            是否强制再连接一次，true:强制重连,false：不强制重连
	 * @return
	 */
	public Connection connection(String host, int port, String username, String password, boolean isForce) {
		if (conns.get(host) != null) {
			if (isForce) {
				conns.get(host).close();
				conns.remove(host);
			} else {
				return conns.get(host);
			}
		}
		Connection conn = new Connection(host, port);
		try {
			conn.connect();
			boolean isAuthenticated = conn.authenticateWithPassword(username, password);
			if (isAuthenticated == false)
				throw new IllegalAccessError(String.format("未授权的用户[%s]", username));
		} catch (IOException e) {
			throw new IllegalAccessError(String.format("连接主机[%s]失败", host));
		}
		conns.put(host, conn);
		return conn;
	}

	/***
	 * 默认端口连接
	 * 
	 * @param host
	 *            主机
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return
	 */
	public Connection connection(String host, String username, String password) {
		return connection(host, 22, username, password, false);
	}

	/***
	 * 从map中拿到连接，适合已做连接的情况
	 * 
	 * @param host
	 *            主机
	 * @return
	 */
	public Connection connection(String host) {
		return conns.get(host);
	}

	public Session getsession(Connection conn) {
		try {
			Session session = conn.openSession();
			return session;
		} catch (IOException e) {
			throw new IllegalAccessError("不能打开session");
		}
	}
}
